import requests
import base64
import urllib
import urllib3
import json
import time
import socket
import os
import openpyxl
import webbrowser
from db import DbUtil

db = DbUtil.DB()


BASE = "http://10.251.52.16:12104"


class ADPM:

    session = requests.Session()

    def __init__(self, user, passwd):
        URL_LOGIN = BASE+"/adpm-web/login"
        passwd = base64.b64encode(passwd.encode())
        LOGIN_DATA = {'loginName': user, 'password': passwd}
        login_html = self.session.post(url=URL_LOGIN, data=LOGIN_DATA)
        try:
            userId = login_html.json().get('data').get('user').get('userId')
        except:
            raise Exception("密码错误")
        # 有代理的使用自己身份登录
        URL_SELECT = BASE+"/adpm-web/proxy/view/switch?userId="+str(userId)
        index = self.session.get(URL_SELECT)

    def GetBrInfo(self, code, brTypes="1"):
        try:
            data1 = {
                'draw': '4',
                'columns[0][data]': 'brCode',
                'columns[0][name]': '',
                'columns[0][searchable]': 'true',
                'columns[0][orderable]': 'false',
                'columns[0][search][value]': '',
                'columns[0][search][regex]': 'false',
                'columns[1][data]': 'oaCode',
                'columns[1][name]': '',
                'columns[1][searchable]': 'true',
                'columns[1][orderable]': 'false',
                'columns[1][search][value]': '',
                'columns[1][search][regex]': 'false',
                'columns[2][data]': 'brName',
                'columns[2][name]': '',
                'columns[2][searchable]': 'true',
                'columns[2][orderable]': 'false',
                'columns[2][search][value]': '',
                'columns[2][search][regex]': 'false',
                'columns[3][data]': 'brType',
                'columns[3][name]': '',
                'columns[3][searchable]': 'true',
                'columns[3][orderable]': 'false',
                'columns[3][search][value]': '',
                'columns[3][search][regex]': 'false',
                'columns[4][data]': 'proposalStage',
                'columns[4][name]': '',
                'columns[4][searchable]': 'true',
                'columns[4][orderable]': 'false',
                'columns[4][search][value]': '',
                'columns[4][search][regex]': 'false',
                'columns[5][data]': 'brProposerSupDept',
                'columns[5][name]': '',
                'columns[5][searchable]': 'true',
                'columns[5][orderable]': 'false',
                'columns[5][search][value]': '',
                'columns[5][search][regex]': 'false',
                'columns[6][data]': 'brContacts',
                'columns[6][name]': '',
                'columns[6][searchable]': 'true',
                'columns[6][orderable]': 'false',
                'columns[6][search][value]': '',
                'columns[6][search][regex]': 'false',
                'columns[7][data]': 'brDept',
                'columns[7][name]': '',
                'columns[7][searchable]': 'true',
                'columns[7][orderable]': 'false',
                'columns[7][search][value]': '',
                'columns[7][search][regex]': 'false',
                'columns[8][data]': 'brChief',
                'columns[8][name]': '',
                'columns[8][searchable]': 'true',
                'columns[8][orderable]': 'false',
                'columns[8][search][value]': '',
                'columns[8][search][regex]': 'false',
                'columns[9][data]': 'brStatus',
                'columns[9][name]': '',
                'columns[9][searchable]': 'true',
                'columns[9][orderable]': 'false',
                'columns[9][search][value]': '',
                'columns[9][search][regex]': 'false',
                'columns[10][data]': 'tmpTaskLastModifyTime',
                'columns[10][name]': '',
                'columns[10][searchable]': 'true',
                'columns[10][orderable]': 'false',
                'columns[10][search][value]': '',
                'columns[10][search][regex]': 'false',
                'columns[11][data]': 'tmpLastBatchNum',
                'columns[11][name]': '',
                'columns[11][searchable]': 'true',
                'columns[11][orderable]': 'false',
                'columns[11][search][value]': '',
                'columns[11][search][regex]': 'false',
                'columns[12][data]': 'tmpDeployedDate',
                'columns[12][name]': '',
                'columns[12][searchable]': 'true',
                'columns[12][orderable]': 'false',
                'columns[12][search][value]': '',
                'columns[12][search][regex]': 'false',
                'columns[13][data]': 'isWorkloadFinishedDate',
                'columns[13][name]': '',
                'columns[13][searchable]': 'true',
                'columns[13][orderable]': 'false',
                'columns[13][search][value]': '',
                'columns[13][search][regex]': 'false',
                'start': '0',
                'length': '1000',
                'search[value]': '',
                'search[regex]': 'false',
                'page': '1',
                'size': '100',
                'brStockFlag': '',
                'myBr': '',
                'brTypes[]': brTypes,
                'showTaskLastModifyTime': 'true',
                'notInBrStatus': '7',
                'likeBrCode': code,
                'likeBrName': '',
                'brDept': '',
                'brProposerSupDept': '',
                'brType': '',
                'brProcStatuss': '',
                'brStatus': ''
            }
            URL_LIST = BASE+"/adpm-web/businessRequirement/json/brListPage/page"
            info = self.session.post(URL_LIST, data=data1)
            brTypesDict = {'1': '维护需求', '2': '项目需求', '3': '年度预算制', '4': '事件问题'}
            rows = info.json().get('rows')
            brId = rows[0].get('brId')
            brCode = rows[0].get('brCode')
            brName = rows[0].get('brName')
            brType = brTypesDict.get(rows[0].get('brType'))
            brProposerSupDept = rows[0].get('brProposerSupDept')
            brProposerSupDept = self.doQueryInfo(
                'brProposerSupDept', brProposerSupDept)
            creUserName = rows[0].get('creUserName')
            brDept = rows[0].get('brDept')
            brDept = self.doQueryInfo('brDept', brDept)
            brChief = rows[0].get('brChief')
            brChief = self.doQueryInfo('brChief', brChief)
            return {'brId': brId, 'brCode': brCode, 'brName': brName, 'brType': brType, 'brProposerSupDept': brProposerSupDept, 'creUserName': creUserName, 'brDept': brDept, 'brChief': brChief}

        except Exception as e:
            if brTypes == "1":
                return self.GetBrInfo(code, brTypes="3")
            if brTypes == "3":
                return self.GetBrInfo(code, brTypes="4")
            if brTypes == "4":
                return self.GetBrInfo(code, brTypes="2")
            return None

    def doQueryInfo(self, query, code):
        # 根据机构ID  用户ID查询中文信息
        try:
            data = {"id": str(code)}
            # 科技部门
            if query == 'brDept':
                res = self.session.post(
                    BASE+'/adpm-web/selModel/loadModel.act?modelName=xdb:orgleafById', data=data)
            # 业务部门
            elif query == 'brProposerSupDept':
                res = self.session.post(
                    BASE+'/adpm-web/selModel/loadModel.act?modelName=xdb:orgleafById', data=data)
            elif query == 'brChief':
                # 科技负责人
                res = self.session.post(
                    BASE+'/adpm-web/selModel/loadModel.act?modelName=xdb:userById', data=data)
            else:
                pass
            res = res.json()[0].get('code_text')
            res = res.split('/')[-1]
            return res
        except Exception as e:
            print(e)
            return None



adpm = ADPM('303508', 'liuqian1204@')



codes = [
    'X20200928000002',
    'X20200903000009',
    'X20200610000001',
    'X20191230000004',
    'X20200324000005',
    'X20201010000008',
    'X20200903000010',
    'X20190403000007',
    'X20200728000046',
    'X20200116000020',
    'X20190621000010',
    'X20200611000002',
    'X20200821000001',
    'X20200324000016',
    'X20200109000014',

]


# for code in codes:
#     res = adpm.GetBrInfo(code)
#     if not res is None:
#         print(" ".join([res.get('brCode'), res.get('brName'), res.get('brType'), res.get('brProposerSupDept'), res.get('creUserName'), res.get('brDept'), res.get('brChief')]))


# sql = "INSERT INTO bbp('id', 'brName', 'month', 'brType', 'ywBranch', 'ywName', 'kjBranch', 'kjName', 'gmFlag', 'gmName', 'csBranch', 'csName', 'testBranch', 'testName', 'gwcFlag', 'wzhFlag', 'dzyzFlag', 'twsFlag', 'gtpFlag', 'timmerFlag', 'sqlFlag', 'otherBranch', 'workCount', 'process', 'planTime', 'realTime', 'note', 'ext1', 'ext2', 'ext3') VALUES ('"+res.get('brCode')+"', '"+res.get('brName')+"', '', '"+res.get('brType')+"', '"+res.get('brProposerSupDept')+"', '"+res.get('creUserName')+"', '"+res.get('brDept')+"', '"+res.get('brChief')+"', '否', '刘乾', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', NULL, NULL, NULL, NULL, NULL)"

# db.doExecute(sql)
# print(db.doQuery("select  * from bbp"))
# print(db)
